<template>
<div class="cart">
  <el-table
    ref="multipleTable"
    :data="tableData"
    tooltip-effect="dark"
    style="width: 100%"
    @selection-change="handleSelectionChange">
    
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
    
    <el-table-column
    	prop="productName"
      label="商品名称"
      width="420">
      <template slot-scope="scope">
      	<div style="display: flex; align-items: center;">
          <el-image
            v-if="scope.row.fromUrl"
            style="width: 100px; height: 100px;"
            :src="scope.row.productImgPath"
            fit="fill">
          </el-image>
          <el-image
            v-else
            style="width: 100px; height: 100px;"
            :src="scope.row.productImgPath && require('@/assets/img/product/' + scope.row.productImgPath)"
            fit="fill">
          </el-image>
	      	<div style="margin: 30px;">
	      		<p>{{ scope.row.productName }}</p>
	      	</div>
      	</div>
		  </template>
    </el-table-column>
    
    <el-table-column
      prop="productPrice"
      label="商品价格"
      width="220">
    </el-table-column>
    
    <el-table-column
    	label="购买数量"
    	width="320">
      <template scope="scope">
		    <el-input-number v-model="scope.row.purchase" :min="1" :max="scope.row.productStock"></el-input-number>
		  </template>
    </el-table-column>

    <el-table-column
      fixed="right"
      label="操作"
      width="220">
      <template slot-scope="scope">
        <el-button
          @click.native.prevent="deleteRow(scope.$index, tableData)"
          type="text"
          size="small">
          移除
        </el-button>
      </template>
    </el-table-column>
  
  </el-table>

  <div style="margin-top: 20px; display: flex; justify-content: space-around; align-items: center">
  	<p>商品总价：<span class="price">￥{{ totalPrice }}.00 </span></p>
    <p>持有托马斯币：<span class="price">{{ userInfo.score }}</span></p>
    <p>使用托马斯币：
      <el-input-number v-model="scoreUsed" :step="100" step-strictly :min="0" :max="totalPrice * 100 <= userInfo.score ? totalPrice * 100 : userInfo.score" label="scoreDiscount"></el-input-number>
      （抵现 <span class="price">￥{{ scoreDiscount }}.00</span>）
    </p>

    <p>待付款：<span class="price">￥{{ paymentAmount }}.00 </span></p>
    <el-button @click="settleAccount" type="primary" :disabled="multipleSelection.length===0">结算</el-button>
  </div>
</div>
</template>

<script>
export default {
  name: "Cart",
  created() {
  	this.userInfo = this.$store.getters.getUser;
    if (this.userInfo === null) {
      this.$message({
        message: '请先登录！',
        type: 'warning'
      });
      this.$router.push("/login");
      return;
    }
    let _this = this;
    let userId = this.userInfo.id;
    _this.$axios.get("/user/" + userId).then((res) => {
      let resData = res.data.data;
      _this.userInfo.score = resData.score;
    })
  	_this.$axios.get("/shopping-cart/" + userId).then((res) => {
  		let resData = res.data.data;
  		for (let idx in resData) {
        let imgPath = resData[idx].productImgPath;
        let fromUrl = false;
        if (imgPath.slice(0, 4) === "http") {
          fromUrl = true;
        }
  			_this.tableData.push({
  				cartItemId: resData[idx].id,
	        productId: resData[idx].productId,
  				productName: resData[idx].productName,
	        productImgPath: resData[idx].productImgPath,
          fromUrl: fromUrl,
          productPrice: resData[idx].productPrice,
          purchase: resData[idx].purchaseQuantity,
          productStock: resData[idx].productStock,
          userId: userId
  			})
  		}
  	});
  },
  data() {
  	return {
  		userInfo: null,
  		tableData: [],
      multipleSelection: [],
      scoreUsed: 0,
  	}
  },
  computed: {
    scoreDiscount() {
      return this.scoreUsed / 100;
    },
  	totalPrice() {
  		let result = 0.0;
  		for (let idx in this.multipleSelection) {
  			let product = this.multipleSelection[idx];
  			result += product.productPrice * product.purchase;
  		}
  		return result;
  	},
    paymentAmount() {
      return this.totalPrice - this.scoreDiscount;
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    deleteRow(index, rows) {
      let _this = this;
      let id = rows[index].cartItemId;

	  	// 从数据库删除
      this.$axios({
	  		method: 'DELETE',
	  		url: '/shopping-cart/delete-batch',
	  		data: [id]
	  	}).then((res) => {
	  		console.log(res);

	  		// 从前端页面删除
	  		rows.splice(index, 1);  
	  	})

    },
    settleAccount() {
      let _this = this;
      let orderSurvey = {
        userId: _this.userInfo.id,
        userName: _this.userInfo.username,
        userAddress: _this.userInfo.address,
        totalPrice: _this.totalPrice,
        discount: _this.scoreDiscount,
        paymentAmount: _this.paymentAmount,
        status: "待支付",
        type: 1
      };
      let orderDetails = [];
      for (let i in this.multipleSelection) {
        let item = this.multipleSelection[i];
        orderDetails.push({
          productId: item.productId,
          productName: item.productName,
          purchaseQuantity: item.purchase,
          productPrice: item.productPrice
        });
      }
      let cartItemIds = [];
      for (let i in this.multipleSelection) {
        cartItemIds.push(this.multipleSelection[i].cartItemId);
      }

      let orderSettlementDto = {
        orderSurvey: orderSurvey,
        orderDetails: orderDetails,
        cartItemIds: cartItemIds
      }

      _this.$axios.post("/order-settlement", orderSettlementDto).then(res => {
        let orderId = res.data.data;
        _this.tableData = _this.tableData.filter(item => {
          return _this.multipleSelection.indexOf(item) < 0;
        });

        _this.$message({
          message: '已成功提交订单！',
          type: 'success'
        });

        _this.$router.push("/payment/" + orderId);
      })
    }
  }
}
</script>

<style scoped>
.cart {
	width: 1242px;
}

.price {
	line-height: 22px; 
	width: 160px; 
	font-size: 16px; 
	color: #d44; 
	font-weight: 900;
}
</style>